package com.crm.smartmachine.ui.common

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.cheng.library.action.StatusAction
import com.cheng.library.common.clickNoRepeat
import com.cheng.library.common.toast
import com.cheng.library.utils.Param
import com.cheng.library.widget.HintLayout
import com.crm.smartmachine.R
import com.crm.smartmachine.base.SmartBaseFragment
import com.crm.smartmachine.bean.request.BhRequest
import com.crm.smartmachine.contants.ActionTypeEnum
import com.crm.smartmachine.contants.Constants
import com.crm.smartmachine.databinding.FragmentChooseGoodsBinding
import com.crm.smartmachine.manager.ModbusManager
import com.crm.smartmachine.manager.callback.WriteRegistersCallback
import com.crm.smartmachine.ui.common.adapter.ChooseGoodsAdapter
import com.crm.smartmachine.viewmodel.MainViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 选择物品
 */
class ChooseGoodsFragment : SmartBaseFragment<FragmentChooseGoodsBinding>(), StatusAction,
    OnItemChildClickListener {

    override fun getLayoutId(): Int? = R.layout.fragment_choose_goods

//    private val viewModel: MainViewModel by viewModel()

    @Param
    private lateinit var action: String

//    @Param
//    private lateinit var wpid: String //物品id

    @Param
    private lateinit var wpbh: String //物品编号

    @Param
    private lateinit var kcsl: String //库存数量

    @Param
    private lateinit var hdbh: String //货道编号

    private val adapter by lazy { ChooseGoodsAdapter() }

    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)

        (binding.recyclerView.itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
        binding.recyclerView.adapter = adapter
        adapter.addChildClickViewIds(
            R.id.ivReduce, R.id.ivAdd
        )
        adapter.setOnItemChildClickListener(this)
        binding.tvSelectedCase.text = "已选择：${hdbh}货道"
        if (action == ActionTypeEnum.SAVE.value) {
            binding.btnStart.text = "取货"
            binding.btnStart.setBackgroundResource(R.drawable.selector_choose_goods_take_btn)
            binding.btnComplete.text = "存货"
            binding.btnComplete.setBackgroundResource(R.drawable.selector_choose_goods_save_btn)
        } else {
            binding.btnStart.text = "开始"
            binding.btnStart.setBackgroundResource(R.drawable.selector_choose_goods_start_btn)
            binding.btnComplete.text = "完成"
            binding.btnComplete.setBackgroundResource(R.drawable.selector_choose_goods_complete_btn)
        }

        observe()
        onClick()

        //接口10：获取物品
        showLoading()
        viewModel.getWp()
    }

    private fun observe() {
//        viewModel.defUI.msgEvent.observe(this) {
//            when (it.msg) {
//                EventConstants.BACK_HOME -> navigateBack()
//            }
//        }
        viewModel.errorResponse.observe(this) {
            handleErrorResponse(it)
            showComplete()
        }
        viewModel.getWpResponse.observe(this) {
            showComplete()
//            if (action == ActionTypeEnum.SAVE.value) {
//                adapter.setList(it)
//            } else { //补货

//                if ((!TextUtils.isEmpty(wpbh) || !TextUtils.isEmpty(wpmc)) && kcsl.toInt() > 0) { //货道里有物品
//                    adapter.setList(it.filter { wp -> (wp.wpbh == wpbh || wp.wpmc == wpmc) })
//                } else {
//                    adapter.setList(it)
//                }
                if (kcsl.toInt() > 0) { //货道里有物品
                    adapter.setList(it.filter { wp -> wp.wpbh == wpbh })
                } else {
                    adapter.setList(it)
                }
//            }
        }
        viewModel.saveGoodsResponse.observe(this) {
            navigateSuccessFragment()
        }
        viewModel.bhResponse.observe(this) {
            navigateSuccessFragment()
        }
    }

    private var isSupplyStarting = false

    private fun onClick() {
        //返回
        binding.actionBarBack.clickNoRepeat {
            navigateBack()
        }
        //开始/取货
        binding.btnStart.clickNoRepeat {
            if (action == ActionTypeEnum.SAVE.value) { //取货
                saveOrTakeGoods("2")
            } else { //开始补货
                if (isSupplyStarting) {
                    ModbusManager.openCase4SupplyStop(hdbh, object : WriteRegistersCallback {
                        override fun onSuccess() {}
                    })
                } else {
                    ModbusManager.openCase4SupplyStart(hdbh, object : WriteRegistersCallback {
                        override fun onSuccess() {}
                    })
                }
                isSupplyStarting = !isSupplyStarting
                binding.btnStart.text = if (isSupplyStarting) "停止" else "开始"
            }
        }
        //完成/存货
        binding.btnComplete.clickNoRepeat {
            if (action == ActionTypeEnum.SAVE.value) { //存货
                saveOrTakeGoods("1")
            } else { //完成补货
                if (adapter.getSelectedPosition() == -1) {
                    toast("请选择物品")
                    return@clickNoRepeat
                }
                val bean = adapter.data[adapter.getSelectedPosition()]
                //接口11：补货接口
//                viewModel.bh(BhRequest(wpwz, hdbh, bean.unid, bean.wpbh, bean.wpmc, bean.count))
                // TODO:
                viewModel.bh(BhRequest("0", hdbh, bean.unid, bean.wpbh, bean.wpmc, bean.count, "1"))
            }
        }
    }

    /**
     * 存/取货
     * @param type 1-存 2-取
     */
    private fun saveOrTakeGoods(type: String) {
        if (adapter.getSelectedPosition() == -1) {
            toast("请选择物品")
            return
        }
        val bean = adapter.data[adapter.getSelectedPosition()]
        //接口11
        viewModel.bh(BhRequest("1", hdbh, bean.unid, bean.wpbh, bean.wpmc, bean.count, type))
//        viewModel.saveGoods(
//            arrayListOf(
//                SaveGoodsRequest(
//                    hdbh,
//                    bean.wpmc,
//                    bean.count.toString(),
//                    type
//                )
//            )
//        )
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val bean = this.adapter.data[position]
        when (view.id) {
            R.id.ivReduce -> {
                if (bean.count > 0) {
                    bean.count--
                }
            }
            R.id.ivAdd -> {
                bean.count++
            }
        }
        this.adapter.setSelectedPosition(position)
        this.adapter.notifyItemChanged(position, Constants.PAYLOAD_TV_GOODS_COUNT)
    }

    private fun navigateSuccessFragment() {
        navigate(R.id.action_chooseGoodsFragment_to_handleGoodsSuccessFragment, Bundle().apply {
            putString("action", action)
        })
    }

    override fun getHintLayout(): HintLayout = binding.hintLayout

}